package com.advance.springcloud.auth.service;

import com.advance.springcloud.auth.domain.SecurityUser;
import com.advance.springcloud.commons.dto.UserDTO;
import com.advance.springcloud.commons.constant.MessageConstant;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户管理业务类
 * 实现SpringSecurity的UserDetailsService接口，用于加载用户信息
 * Created by advance on 2021/3/19.
 */
@AllArgsConstructor
@Service
public class UserServiceImpl implements UserDetailsService {

    //模拟使用测试数据
    private List<UserDTO> userList;

    private PasswordEncoder passwordEncoder;

    //初始化放入几个测试数据
    @PostConstruct
    public void initData(){
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new UserDTO(1L,"macro", password,1, Arrays.asList("ADMIN")));
        userList.add(new UserDTO(2L,"andy", password,1, Arrays.asList("TEST")));
    }

    /**
     * 加载登录用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<UserDTO> userDTOList = userList.stream().filter(item -> item.getUsername().equals(username)).collect(Collectors.toList());
        //用户信息不存在，则返回错误信息 USERNAME_PASSWORD_ERROR
        if (CollectionUtils.isEmpty(userDTOList)) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        //获取用户信息
        SecurityUser securityUser = new SecurityUser(userDTOList.get(0));
        //用户信息不可用
        if(!securityUser.isEnabled()){
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        }
        //账户信息被锁
        else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //账号过期
        else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        }
        //登陆过期
        else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }
}
